(function (doc) {
  var searchInput = doc.getElementsByClassName('J_searchInput')[0],
    wdList = doc.getElementsByClassName('J_wdList')[0],
    listWrap = wdList.parentNode,
    listTpl = doc.getElementById('J_listTpl').innerHTML;

  // console.log(searchInput, wdList, listWrap, listTpl);

  var init = function () {
    bindEvent();
  };

  function bindEvent() {
    searchInput.addEventListener('input', typeInput, false);
  }

  function typeInput() {
    var val = _trimSpace(this.value),
      len = val.length;

    if (len > 0) {
      getDatas(val, 'setDatas');
    } else {
    }
  }

  /**
   *
   * @param {*} value 输入的value值
   * @param {*} callbackName 回调函数名称
   */
  function getDatas(value, callbackName) {
    var oScript = doc.createElement('script');
    oScript.src = `https://www.baidu.com/sugrec?&prod=pc&wd=${value}&cb=${callbackName}`;
    doc.body.appendChild(oScript);
    doc.body.removeChild(oScript);
  }

  function _trimSpace(str) {
    //所有字符匹配0次或1次全局,替换为空
    return str.replace(/\s+/g, '');
  }

  //window.setDatas函数是将jsonp执行时找到的当前函数
  window.setDatas = function (data) {
    // console.log(data);
    //{q: '饿了么', p: false, g: Array(10), slid: '265527256434550', queryid: '0x144f17ee1cc4776'}
    renderList(data);
  };

  function renderList(data) {
    var list = '',
      data = data.g,
      len = data.length;

    if (len > 0) {
      data.forEach(function (elem) {
        list += listTpl.replace(/{{(.*?)}}/g, function (node, key) {
          return {
            wdLink: elem.q,
            wd: elem.q
          }[key];
        });
        wdList.innerHTML = list;
        listWrap.style.display = 'block';
      });
    } else {
      wdList.innerHTML = '';
      listWrap.style.display = 'none';
    }
  }

  init();
})(document);
